using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class SimpleHttpServer
{
    private HttpListener listener;
    private UpdateManager updateManager;
    private bool isRunning;

    public SimpleHttpServer(UpdateManager manager, int port = 8080)
    {
        updateManager = manager;
        listener = new HttpListener();
        listener.Prefixes.Add($"http://+:{port}/");
    }

    public void Start()
    {
        try
        {
            listener.Start();
            isRunning = true;
            Task.Run(() => HandleRequests());
        }
        catch { }
    }

    public void Stop()
    {
        isRunning = false;
        listener?.Stop();
    }

    private async Task HandleRequests()
    {
        while (isRunning)
        {
            try
            {
                var context = await listener.GetContextAsync();
                _ = Task.Run(() => ProcessRequest(context));
            }
            catch { }
        }
    }

    private async Task ProcessRequest(HttpListenerContext context)
    {
        try
        {
            var request = context.Request;
            var response = context.Response;

            if (request.Url?.AbsolutePath == "/api/iis/sites")
            {
                var progress = new Progress<string>();
                var sites = await updateManager.CollectIISServices(progress);

                var remoteSites = sites.ConvertAll(s => new RemoteIISService
                {
                    SiteName = s.SiteName,
                    SiteId = (int)s.SiteId,
                    State = s.State,
                    PhysicalPath = s.PhysicalPath ?? "",
                    Bindings = s.Bindings ?? "",
                    Port = int.TryParse(s.Bindings?.Split(':')[1].Split('/')[0], out int port) ? port : 80,
                    MachineName = Environment.MachineName,
                    MachineIP = GetLocalIP()
                });

                var json = JsonConvert.SerializeObject(remoteSites);
                var buffer = Encoding.UTF8.GetBytes(json);

                response.ContentType = "application/json";
                response.ContentLength64 = buffer.Length;
                await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
            }
            else
            {
                response.StatusCode = 404;
            }

            response.Close();
        }
        catch { }
    }

    private string GetLocalIP()
    {
        try
        {
            var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    return ip.ToString();
            }
        }
        catch { }
        return "127.0.0.1";
    }
}
